﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using YGBookmark.DAL;
using YGBookmark.Models;

namespace YGBookmark.UI
{
    /// <summary>
    /// 书签编辑窗体（支持富文本编辑和标签管理）
    /// </summary>
    public partial class EditForm : Form
    {
        #region 控件声明
        private TableLayoutPanel mainLayout;
        private TextBox txtUrl;
        private TextBox txtTitle;
        private TextBox txtSummary;
        private PictureBox picCover;
        private CheckedListBox clbTags;
        private RichTextBox txtRemark;
        private Button btnSave;
        private Button btnCancel;
        private Button btnBrowseImage;
        private OpenFileDialog openFileDialog;
        #endregion

        public Bookmark CurrentBookmark { get; private set; }
        private List<Tag> AllTags = new List<Tag>();

        public EditForm(Bookmark bookmark = null)
        {
            CurrentBookmark = bookmark ?? new Bookmark("", "");
            InitializeComponent();
            InitializeUI();
            LoadDataAsync();
        }

        #region UI初始化
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.AutoScaleDimensions = new SizeF(6F, 12F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(800, 600);
            this.Text = CurrentBookmark.Id == 0 ? "新建书签" : "编辑书签";
            this.ResumeLayout(false);
        }

        private void InitializeUI()
        {
            mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 6,
                Padding = new Padding(10),
                CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
            };

            // 控件初始化
            txtUrl = CreateTextField("URL:", 500);
            txtTitle = CreateTextField("标题:", 200);
            txtSummary = CreateTextField("摘要:", 1000);
            txtRemark = new RichTextBox { Dock = DockStyle.Fill, ScrollBars = RichTextBoxScrollBars.Vertical };
            picCover = new PictureBox { Dock = DockStyle.Fill, SizeMode = PictureBoxSizeMode.Zoom };
            clbTags = new CheckedListBox { Dock = DockStyle.Fill, CheckOnClick = true };
            btnBrowseImage = new Button { Text = "选择图片...", AutoSize = true };
            btnSave = new Button { Text = "保存", BackColor = Color.SteelBlue, ForeColor = Color.White };
            btnCancel = new Button { Text = "取消", BackColor = Color.Gray, ForeColor = Color.White };

            // 事件绑定
            btnBrowseImage.Click += BrowseImage;
            btnSave.Click += async (s, e) => await SaveBookmark();
            btnCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;

            // 布局设置
            AddRow("URL:", txtUrl);
            AddRow("标题:", txtTitle);
            AddRow("摘要:", txtSummary);
            AddRow("封面图:", new Panel { Dock = DockStyle.Fill }
                .WithChildren(picCover, btnBrowseImage));
            AddRow("标签:", clbTags);
            AddRow("备注:", txtRemark);

            // 按钮面板
            var btnPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Bottom,
                FlowDirection = FlowDirection.RightToLeft,
                Height = 40,
                Padding = new Padding(0, 5, 0, 0)
            };
            btnPanel.Controls.AddRange(new[] { btnCancel, btnSave });

            this.Controls.Add(mainLayout);
            this.Controls.Add(btnPanel);
            this.AcceptButton = btnSave;
            this.CancelButton = btnCancel;
        }

        private void AddRow(string labelText, Control control)
        {
            mainLayout.Controls.Add(new Label
            {
                Text = labelText,
                AutoSize = true,
                Anchor = AnchorStyles.Left | AnchorStyles.Top
            });
            mainLayout.Controls.Add(control);
        }

        private TextBox CreateTextField(string placeholder, int maxLength)
        {
            return new TextBox
            {
                Dock = DockStyle.Fill,
                MaxLength = maxLength,
                Tag = placeholder,
                ForeColor = SystemColors.GrayText
            }.WithPlaceholder(placeholder);
        }
        #endregion

        #region 数据操作
        private async void LoadDataAsync()
        {
            try
            {
                if (this.CurrentBookmark.Id > 0)
                {
                    var lt = await DatabaseHelper.Instance.ExecuteQueryAsync<Tag>($"SELECT * FROM Tags where Id in (select TagId from BookmarkTags where BookmarkId={this.CurrentBookmark.Id})");
                    foreach (var m in lt)
                    {
                        CurrentBookmark.AddTag(m);
                    }
                }

                // 加载所有标签
                AllTags = await DatabaseHelper.Instance.ExecuteQueryAsync<Tag>("SELECT * FROM Tags");
                clbTags.Items.Clear();
                foreach (var tag in AllTags)
                {
                    clbTags.Items.Add(tag.Name, CurrentBookmark.BookmarkTags.Any(bt => bt.TagId == tag.Id));
                }

                // 绑定数据
                txtUrl.Text = CurrentBookmark.Url;
                txtTitle.Text = CurrentBookmark.Title;
                txtSummary.Text = CurrentBookmark.Summary;
                txtRemark.Text = CurrentBookmark.Remark;
                LoadCoverImage(CurrentBookmark.CoverImage);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"数据加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadCoverImage(string imagePath)
        {
            try
            {
                if (File.Exists(imagePath))
                {
                    picCover.Image = Image.FromFile(imagePath);
                }
                else if (!string.IsNullOrWhiteSpace(imagePath))
                {
                    picCover.LoadAsync(imagePath);
                }
            }
            catch
            {
                try
                {
                    var dc = Properties.Resources.DefaultCover;
                    using (var stream = new MemoryStream(dc))
                    {
                        picCover.Image = Image.FromStream(stream);
                    }
                }
                catch { }
            }
        }

        private async Task SaveBookmark()
        {
            if (!ValidateInput()) return;

            try
            {
                UpdateBookmarkFromUI();

                // 保存书签
                if (CurrentBookmark.Id == 0)
                {
                    CurrentBookmark.Id = Convert.ToInt32(await DatabaseHelper.Instance.ExecuteScalarAsync(
                        "INSERT INTO Bookmarks (Url, Title, Summary, CoverImage, Remark, CreateTime) " +
                        "VALUES (@url, @title, @summary, @cover, @remark, @ct); SELECT last_insert_rowid();",
                        GetBookmarkParameters()));
                }
                else
                {
                    await DatabaseHelper.Instance.ExecuteNonQueryAsync(
                        "UPDATE Bookmarks SET Url=@url, Title=@title, Summary=@summary, " +
                        "CoverImage=@cover, Remark=@remark WHERE Id=@id",
                        GetBookmarkParameters().Concat(new[] { new SQLiteParameter("@id", CurrentBookmark.Id) }));
                }

                // 保存标签关联
                await UpdateTagsAsync();

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private SQLiteParameter[] GetBookmarkParameters()
        {
            return new[]
            {
                new SQLiteParameter("@url", txtUrl.Text.Trim()),
                new SQLiteParameter("@title", txtTitle.Text.Trim()),
                new SQLiteParameter("@summary", txtSummary.Text.Trim()),
                new SQLiteParameter("@cover", CurrentBookmark.CoverImage),
                new SQLiteParameter("@remark", txtRemark.Text.Trim()),
                new SQLiteParameter("@ct", DateTime.Now)
            };
        }

        private async Task UpdateTagsAsync()
        {
            var selectedTags = clbTags.CheckedItems.Cast<string>();
            var currentTagIds = CurrentBookmark.BookmarkTags.Select(bt => bt.TagId).ToList();

            // 删除不再选中的标签
            foreach (var tag in AllTags.Where(t => !selectedTags.Contains(t.Name) && currentTagIds.Contains(t.Id)))
            {
                await DatabaseHelper.Instance.ExecuteNonQueryAsync(
                    "DELETE FROM BookmarkTags WHERE BookmarkId=@bid AND TagId=@tid",
                    new SQLiteParameter("@bid", CurrentBookmark.Id),
                    new SQLiteParameter("@tid", tag.Id));
            }

            // 添加新选中的标签
            foreach (var tag in AllTags.Where(t => selectedTags.Contains(t.Name) && !currentTagIds.Contains(t.Id)))
            {
                await DatabaseHelper.Instance.ExecuteNonQueryAsync(
                    "INSERT INTO BookmarkTags (BookmarkId, TagId) VALUES (@bid, @tid)",
                    new SQLiteParameter("@bid", CurrentBookmark.Id),
                    new SQLiteParameter("@tid", tag.Id));
            }
        }
        #endregion

        #region 交互逻辑
        private void BrowseImage(object sender, EventArgs e)
        {
            openFileDialog = new OpenFileDialog
            {
                Filter = "图片文件|*.jpg;*.jpeg;*.png;*.gif|所有文件|*.*",
                Title = "选择封面图片"
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                CurrentBookmark.CoverImage = openFileDialog.FileName;
                LoadCoverImage(openFileDialog.FileName);
            }
        }

        private bool ValidateInput()
        {
            var errors = new List<string>();

            if (string.IsNullOrWhiteSpace(txtUrl.Text))
                errors.Add("URL不能为空");
            else if (!Uri.IsWellFormedUriString(txtUrl.Text, UriKind.Absolute))
                errors.Add("URL格式不正确");

            if (string.IsNullOrWhiteSpace(txtTitle.Text))
                errors.Add("标题不能为空");

            if (errors.Any())
            {
                MessageBox.Show(string.Join("\n", errors), "输入验证失败",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
        }

        private void UpdateBookmarkFromUI()
        {
            CurrentBookmark.Url = txtUrl.Text.Trim();
            CurrentBookmark.Title = txtTitle.Text.Trim();
            CurrentBookmark.Summary = txtSummary.Text.Trim();
            CurrentBookmark.Remark = txtRemark.Text.Trim();
        }
        #endregion
    }

    #region 扩展方法
    public static partial class ControlExtensions
    {
        public static T WithPlaceholder<T>(this T textBox, string placeholder) where T : TextBox
        {
            textBox.Enter += (s, e) =>
            {
                if (textBox.Text == placeholder)
                {
                    textBox.Text = "";
                    textBox.ForeColor = SystemColors.WindowText;
                }
            };

            textBox.Leave += (s, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = placeholder;
                    textBox.ForeColor = SystemColors.GrayText;
                }
            };

            textBox.Text = placeholder;
            return textBox;
        }

        //public static Control WithChildren(this Control parent, params Control[] children)
        //{
        //    foreach (var child in children)
        //    {
        //        parent.Controls.Add(child);
        //    }
        //    return parent;
        //}
    }
    #endregion
}
